package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @desc 验证码的操作
 * @Date 2020/10/18 21:23
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {



    //本地注入redis连接池
    @Autowired
    private JedisPool jedisPool;



    /**
     * 手机预约的验证码校验
     * @param telephone 电话号码
     * @return
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        //随机生成四位数的验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        try {
            //调用发送短信的方法，传入数据发短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            //将验证码保存到redis，一会进行比对   fixme  时间需要改正
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,30000000,validateCode.toString());

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }


    /**
     * 用户登录的手机验证
     * @param telephone 手机号码
     * @return
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //随机生成四位数的验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        try {
            //调用发送短信的方法，传入数据发短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            //将验证码保存到redis，一会进行比对  fixme  时间需要改正
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,30000000,validateCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);

        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }


}
